package com.example.game.module.service;

import com.example.game.module.entity.User;
import com.example.game.module.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;


@Service
public class UserService {

    private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Autowired
    private UserMapper userMapper;

    public User getById(Long userId) {

        return userMapper.getById(userId);
    }

    public User extractById(Long userId) {

        return userMapper.extractById(userId);
    }

    public Integer insert(User entity) {

        return userMapper.insert(entity);
    }

    public Integer update(User entity) {

    return userMapper.update(entity);
    }

    public Integer delete(Long id, Integer updateTime) {

        return userMapper.delete((int)(System.currentTimeMillis() / 1000), id);
    }

    public User register(String phone, String password, String name,String avatar) {

        validateParameters(phone,password,name,avatar);
        if (userMapper.getByPhone(phone) != null) {
            throw new RuntimeException("手机号已注册");
        }
        User user = new User();
        user.setPhone(phone);
        user.setPassword(passwordEncoder.encode(password)); // 加密密码
        user.setName(name);
        user.setAvatar(avatar);
        user.setCreateTime((int)(System.currentTimeMillis() / 1000));
        user.setUpdateTime((int)(System.currentTimeMillis() / 1000));
        userMapper.insert(user);
        return user;
    }

    private void validateParameters(String phone, String password, String name,  String avatar) {
        if (phone == null || phone.isEmpty()) {
            throw new RuntimeException("电话不能为空");
        }
        if (password == null || password.isEmpty()) {
            throw new RuntimeException("密码不能为空");
        }
        if (name == null || name.isEmpty()) {
            throw new RuntimeException("名字不能为空");
        }
        if (avatar == null || avatar.isEmpty()) {
            throw new RuntimeException("头像不能为空");
        }
    }

    public User login(String phone, String password) {
        User user = userMapper.getByPhone(phone);
        if (user == null || !passwordEncoder.matches(password, user.getPassword())) {
            throw new RuntimeException("手机号或密码错误");
        }
        return user;
    }


}

